package com.example.state.machine.handler;

import com.example.state.machine.enums.OrderEvent;
import com.example.state.machine.enums.OrderState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.statemachine.StateMachineContext;
import org.springframework.statemachine.StateMachinePersist;
import org.springframework.statemachine.support.DefaultStateMachineContext;
import org.springframework.stereotype.Component;

// 状态持久化
@Component
public class OrderStatePersist implements StateMachinePersist<OrderState, OrderEvent, Long> {

    @Autowired
    private OrderRepository orderRepository;

    @Override
    public void write(StateMachineContext<OrderState, OrderEvent> context, Long orderId) {
        // 将状态保存到数据库
        Order order = orderRepository.findById(orderId).orElseThrow();
        order.setState(context.getState());
        orderRepository.save(order);
    }

    @Override
    public StateMachineContext<OrderState, OrderEvent> read(Long orderId) {
        // 从数据库恢复状态
        Order order = orderRepository.findById(orderId).orElseThrow();
        return new DefaultStateMachineContext<>(order.getState(), null, null, null);
    }
}